import axios from 'axios'
import Router from '@/router/index'
import config from '../config'
import {
    getToken,
    setToken,
    getTokenType,
    getMenucode,
    getTimeDateNow
} from "./common"
import store from "../store"
import {
    message
} from '@/utils/resetMessage';
axios.defaults.timeout = 60000;
axios.defaults.headers['content-type'] = 'application/json';
axios.defaults.baseURL = config.baseUrl;

function handleCode(code) {
    let config = {
        400: '接口请求错误，请联系管理员！',
        401: '登录过期，请重新登录！',
        403: '很抱歉，您的访问权限等级不够，联系管理员!',
        404: '请求地址不存在！',
        409: '接口请求错误！',
        415: '参数校验错误！',
        422: '参数校验不通过！',
        500: '服务器错误，请联系管理员',
        'timeout':"请求超时！"
    };
    message.error(config[code]);
    switch (code) {
        case 403:
            Router.push('/403')
            store.dispatch('deleteCurrentPageTag')
            break;
        case 401:
            Router.push('/login')
            store.dispatch('handleLogOut')
            break;
        case 500:
            Router.push('/500')
            break;
        default:
            break;
    }
}
// 添加请求拦截器
axios.interceptors.request.use(
    function (config) {
        config.headers['Authorization'] = getTokenType() + ' ' + getToken();
        return config;
    },
    function (error) {
        
        return Promise.reject(error);
    }
);


// 添加响应拦截器
axios.interceptors.response.use(
    (response) => {
        if (response.config.responseType === 'blob') {
            let routesChildren = Router.options.routes[0].children
            let menuItem = routesChildren.find(item=>{
                return item.name == getMenucode() 
            })
            response.fileName = menuItem.meta.title + '（' + getTimeDateNow() + '）.xlsx'
        }
        return response
    },
    (error) => {
        let originalRequest = error.config
        if (error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1 && !originalRequest._retry) {
            handleCode('timeout')
            return Promise.reject({
                data:{
                    code:"timeout",
                }
            })
        }
        handleCode(error.response.status)
        return Promise.reject(error);
    }
);

/**
 *
 * @param option    请求参数
 * @returns {AxiosPromise<any>}
 */
const request = (option) => {
    return new Promise((resolve, reject) => {
        axios.request(option).then(res => {
            if (res.data.code === 50109) {
                refreshToken()
            }
            return resolve(res)
        }).catch(e => {
            message.error('服务器错误，请稍后再试！')
            reject(e)
        })
    })
}

export default request